import wx from 'weixin-js-sdk-ts';
import { post } from '@/utils/request';
import { Dialog } from 'vant';
export default {
    getQuery: (para: string) => {
        let str = document.location.href;
        let r = str.match(new RegExp("[\\?&]" + para + "=([^&]*)", "i"))
        return r ? decodeURIComponent(r[1]) : ''
    },
    setWxConfig: (url: string) => {
        return new Promise((resolve, reject) => {
            post("wxSign", { 'url': url }).then((res: any) => {
                if (res.code == 0) {
                    resolve(true);
                    wx.config({
                        debug: false,
                        appId: res.data.appid,
                        timestamp: res.data.timestamp,
                        nonceStr: res.data.noncestr,
                        signature: res.data.signature,
                        jsApiList: ['chooseWXPay', 'getLocation', 'openLocation', 'updateAppMessageShareData'],
                        openTagList: ['wx-open-launch-weapp']
                    });
                }
            });
        })

    },
    getToken() {
        return localStorage.getItem("token");
    },
    setToken(value: string) {
        localStorage.setItem("token", value);
    },
    getUserId() {
        return localStorage.getItem("userId");
    },
    setUserId(value: string) {
        localStorage.setItem("userId", value);
    },
    getLocation() {
        return sessionStorage.getItem("location");
    },
    setLocation(value: string) {
        sessionStorage.setItem("location", value);
    },
    getCode() {
        window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx5b58503deb70471d&redirect_uri=${encodeURIComponent(document.location.href)}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`;
    },
    getAuthToken(callback: Function) {
        // this.setToken('bdc8e3f8cb9ac57934abe19ed6580459');
        // this.setUserId("60");
        // this.setLocation(JSON.stringify({ latitude: '30.66348', longitude: '104.07450' }));

        let code = this.getQuery("code");
        let cardNumber = this.getQuery("cardNumber");
        let cardPwd = this.getQuery("cardPwd");

        if (cardNumber != "") {
            localStorage.clear();
        }

        if (this.getToken() != null && this.getUserId() != null) {
            callback();
            return;
        }

        if (code == '') {
            this.getCode();
            return;
        }
        post(`authorizationCode`, {
            "cardNumber": cardNumber,
            "cardPwd": cardPwd,
            "jsCode": code
        })
            .then(res => {
                if (res.code == 0) {
                    this.setToken(res.data.token);
                    this.setUserId(res.data.userId);
                    if (res.data.subscribe == 0) {
                        Dialog.alert({
                            title: '温馨提示',
                            message: '您还没有关注公众号，赶快去关注吧？',
                        }).then(() => {
                            window.location.href = "https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=Mzg2MjUxNzEzMQ==&scene=110#wechat_redirect"
                        });
                    } else {
                        if (cardNumber != '' && cardPwd != '') {
                            window.location.replace(window.location.href.replace(`?cardNumber=${cardNumber}&cardPwd=${cardPwd}&code=${code}&state=STATE`, ''));
                        } else if (code != '') {
                            window.location.replace(window.location.href.replace(`?code=${code}&state=STATE`, ''));
                        } else {
                            callback();
                        }
                    }
                }
            })
            .catch(err => {
                console.log(err);
            });
    },
    getExactTime(time: number) {
        var date = new Date(time * 1000);
        var year = date.getFullYear() + '年';
        var month = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '月';
        var dates = date.getDate() + '日';
        var h = date.getHours();
        var mm = date.getMinutes();
        var s = date.getSeconds();
        return year + month + dates+' ' + h + ':' + mm + ':' + s;
    },
    formatMoney(e: number): string {
        return (e / 100).toFixed(2);
    }
}





